# coding:utf-8
from __future__ import absolute_import
from src.geo_func import way2tiles
from src.osm import Xapi
from src.google_tile import download_tiles
import argparse
import os
import logging
from src import conf
import traceback
import random
from glob import glob


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('xml_file')
    parser.add_argument('img_dir')
    parser.add_argument('-c', '--class-dir-name', help="default=xml_file name")
    parser.add_argument('-l', '--limit', help="limitation for image number", type=int)
    parser.add_argument('--china-convert', default=True, type=bool)
    args = parser.parse_args()
    if args.class_dir_name is None:
        args.class_dir_name, _ = os.path.splitext(os.path.basename(args.xml_file))
    return args


def log_config():
    logging.basicConfig(level=logging.INFO)


def main(args):
    xapi = Xapi()
    ways = xapi.process_one_file_for_ways(args.xml_file)
    save_path = os.path.join(args.img_dir, args.class_dir_name)
    if os.path.exists(save_path) is False:
        os.makedirs(save_path)

    count = len(glob(os.path.join(save_path, "*.jpg")))
    if count != 0:
        logging.warning("There are already %d images in %s" % (count, save_path))

    """第一次打乱，把所有的way打乱。防止样本集中在某个小区域里。"""
    random.shuffle(ways)

    logging.warning('China GCJ-02 convert state: ' + str(args.china_convert))

    for i, way in enumerate(ways):
        try:
            if args.limit is not None and count > args.limit:
                logging.warning('Break because of the limitation.')
                break

            tiles = way2tiles(way, china_convert=args.china_convert)

            """第二次打乱: way内部随机打乱，防止样本集中在这个way的边缘区域"""
            random.shuffle(tiles)

            new_downloaded_num = download_tiles(tiles, save_path, max_downloaded=conf.MAX_SAMPLE_NUM_EACH_WAY)
            count += new_downloaded_num
            if new_downloaded_num != 0:
                logging.info('%d images downloaded to %s.' % (count, save_path))
            logging.info('%d / %d processed.' % (i + 1, len(ways)))
        except Exception:
            logging.error('Error: ' + traceback.format_exc())
    logging.info('Total %d images were downloaded.' % count)
    logging.info('------------------------------------------------------------------')

if __name__ == '__main__':
    log_config()
    args = parse_args()
    main(args)
